package cn.iocoder.yudao.module.ao.dal.mysql.patrol;

import java.util.*;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX;
import cn.iocoder.yudao.module.ao.dal.dataobject.patrol.PatrolDO;
import org.apache.ibatis.annotations.Mapper;
import cn.iocoder.yudao.module.ao.controller.admin.patrol.vo.*;

/**
 * 巡班违纪记录 Mapper
 *
 * @author 智教云枢
 */
@Mapper
public interface PatrolMapper extends BaseMapperX<PatrolDO> {

    default PageResult<PatrolDO> selectPage(PatrolPageReqVO reqVO) {
        LambdaQueryWrapperX<PatrolDO> query = new LambdaQueryWrapperX<PatrolDO>()
                .betweenIfPresent(PatrolDO::getClassDate, reqVO.getClassDate())
                .betweenIfPresent(PatrolDO::getClassTime, reqVO.getClassTime())
                .likeIfPresent(PatrolDO::getCourseName, reqVO.getCourseName())
                .eqIfPresent(PatrolDO::getTeacherId, reqVO.getTeacherId())
                .likeIfPresent(PatrolDO::getTeacherName, reqVO.getTeacherName())
                .eqIfPresent(PatrolDO::getPatrolTeacherId, reqVO.getPatrolTeacherId())
                .likeIfPresent(PatrolDO::getPatrolTeacherName, reqVO.getPatrolTeacherName())
                .eqIfPresent(PatrolDO::getClassroom, reqVO.getClassroom());
        
        // 权限控制:普通老师可以看到两种记录
        // 1. 自己授课的违纪记录(teacher_name匹配)
        // 2. 自己班级的违纪记录(教室列表匹配)
        boolean hasTeacherFilter = reqVO.getCurrentTeacherName() != null;
        boolean hasClassroomFilter = reqVO.getClassrooms() != null && !reqVO.getClassrooms().isEmpty();
        
        if (hasTeacherFilter || hasClassroomFilter) {
            query.nested(w -> {
                if (hasTeacherFilter) {
                    w.eq(PatrolDO::getTeacherName, reqVO.getCurrentTeacherName());
                }
                if (hasClassroomFilter) {
                    if (hasTeacherFilter) {
                        w.or();
                    }
                    w.in(PatrolDO::getClassroom, reqVO.getClassrooms());
                }
            });
        }
        
        return selectPage(reqVO, query
                .eqIfPresent(PatrolDO::getViolationType, reqVO.getViolationType())
                .eqIfPresent(PatrolDO::getViolationDesc, reqVO.getViolationDesc())
                .eqIfPresent(PatrolDO::getViolationCount, reqVO.getViolationCount())
                .eqIfPresent(PatrolDO::getStatus, reqVO.getStatus())
                .betweenIfPresent(PatrolDO::getCreateTime, reqVO.getCreateTime())
                .orderByDesc(PatrolDO::getId));
    }

}